#include "auto_feed.h"
#if (COMPLIE_AUTO_FEED == 1)
#define LED_OPEN  1
#define LED_CLOSE 0

void led_work_cb(cc_work* work, void* work_data)
{
  uint8_t have_pet, low_light_flag = 0;
  user_device_t infrared = cc_device_get(devices, CC_DEVICE_TYPE_INFRARED, 1);
  user_device_t photosensitive = cc_device_get(devices, CC_DEVICE_TYPE_PHOTOSENSITIVE, 1);
  user_device_t led = cc_device_get(devices, CC_DEVICE_TYPE_LED, 1);
  infrared->read_cb(infrared, CC_NULL, 0, &have_pet);
  photosensitive->read_cb(photosensitive, CC_NULL, 0, &low_light_flag);
  if (have_pet = 0 || low_light_flag == 0)
  {
    cc_log("led close\r\n");
    led->control_cb(led, "0", LED_CONTROL_BRIGHT, CC_NULL);
  }
  else
  {
    cc_log("condition satisified continue submit\r\n");
    cc_work_submit(work, 5000);
  }
  return;
}

void led_thread(void* data)
{
  cc_work led_work;
  user_device_t infrared = cc_device_get(devices, CC_DEVICE_TYPE_INFRARED, 1);
  user_device_t photosensitive = cc_device_get(devices, CC_DEVICE_TYPE_PHOTOSENSITIVE, 1);
  uint8_t have_pet = 0xff, low_light_flag = 0xff;
  uint8_t have_pet_last = 0xff, low_light_flag_last = 0xff;

  infrared->num_data[0] = have_pet;
  photosensitive->num_data[0] = low_light_flag;

  user_device_t led = cc_device_get(devices, CC_DEVICE_TYPE_LED, 1);
  cc_work_init(&led_work, led_work_cb, CC_NULL);
  while (1)
  {
    // 1 -> 0跳变一次 代表宠物走了或者环境光不满足了

    infrared->read_cb(infrared, CC_NULL, 0, &have_pet);
    photosensitive->read_cb(photosensitive, CC_NULL, 0, &low_light_flag);
    cc_log_d("test:%d %d\r\n", have_pet, low_light_flag);
    if ((low_light_flag == 1 && low_light_flag == 0) || (have_pet == 1 && have_pet_last == 0))
    {
      cc_log("env change submit close detact work\r\n");
      cc_work_submit(&led_work, 5000);
    }
    if (low_light_flag == 1 && have_pet == 1 && led->state != LED_OPEN)
    {
      cc_log("led open\r\n");
      led->state = LED_OPEN;
      led->control_cb(led, CC_NULL, LED_CONTROL_WHITE, CC_NULL);
    }
    have_pet_last = have_pet;
    low_light_flag_last = low_light_flag;
    cc_delay(100);
  }
}
CC_THREAD_REGISTER(led_thread, 5, 2048)

#endif